<template>
  <div class='confirmOrder'
       :class="[store.isIphoneX?'iphoneX-fixed-bottom-pad':'']">
    <form @submit="submitOrder"
          report-submit='true'>
      <div class='address'
           v-if='address'
           @click="goTo('/pages/user/address')">
        <div class='card-num'
             v-if='shoppingListData'>

          <img src="/static/image/car@2x.png"
               alt="">
          <span>{{shoppingListData[0].title.KH_bianHao}}</span>
        </div>
        <div class='consignee'>
          <div>
            <img src="/static/image/user@2x.png"
                 alt="">
            <span>{{address.DianHuaHao}}</span>
          </div>
          <div>
            <span>{{address.LianXiRen}}</span>

          </div>
        </div>
        <div class="receiving-address">

          <img src="/static/image/address@2x.png"
               alt="">
          <span>{{address.Dizhi}}
          </span>
        </div>

      </div>
      <div class='agreedTime'>
        <div class='select'>
          约定时间
          <input type="">
          <div class='selector'
               v-if='newTimeStamps'>
            <picker mode="selector"
                    :range="newTimeStamps"
                    @change="_newTimeStampsChange">
              {{newTimeStamps[timeStampsIndex]}}
            </picker>
          </div>
        </div>
        <div class='remarks'>
          备注说明
          <input type="text"
                 v-model='leaveWord'>

        </div>
      </div>
      <div class='purchaseGoods'
           v-for='item in shoppingListData'
           :key='item'>
        <ul class='goods-list'>
          <!-- 普通商品 -->
          <li v-for="(items,indexs) in item.arr"
              :key='indexs'>
            <!-- <div class='check'>
            <div>
              <icon :type="items.isSelect?'success_no_circle':''"
                    :size="store.check.size"
                    :color="store.check.color" />
            </div>
          </div> -->
            <div class='content'>
              <div class='lf-img'>
                <img :src="items.SP_Picture"
                     mode="widthFix"
                     alt="">
              </div>
              <div class='rt-goodsInfo'>
                <div>【{{items.HuoHao}}】{{items.SPMingcheng}}</div>
                <!-- <div>
                <span>起送量>=30桶</span>
              </div> -->
                <div class='number'>
                  <span v-if='items.BJ_price>0'>￥{{items.BJ_price}}</span>
                  <span v-else>赠品</span>
                  <div class='number'>
                    ×{{items.number}}{{items.SPDanWei}}
                  </div>
                </div>
              </div>
            </div>
          </li>
          <!-- 标准商品 -->
          <li v-for="(items,indexs) in item.bzArr"
              :key='indexs'>
            <!-- <div class='check'>
            <div>
              <icon :type="items.isSelect?'success_no_circle':''"
                    :size="store.check.size"
                    :color="store.check.color" />
            </div>
          </div> -->
            <div class='content'>
              <div class='lf-img'>
                <img :src="items.Pic"
                     mode="widthFix"
                     alt="">
              </div>
              <div class='rt-goodsInfo'>
                <div>【{{items.HuoHao}}】{{items.SPMingCheng}}</div>
                <!-- <div>
                <span>起送量>=30桶</span>
              </div> -->
                <div class='number'>
                  <span v-if='items.SP_price>0'>￥{{items.SP_price}}</span>
                  <span v-else>0</span>
                  <div class='number'>
                    ×{{items.number}}{{items.SPDanWei}}
                  </div>
                </div>
              </div>
            </div>
          </li>
        </ul>
      </div>
      <div class='stone'></div>
      <div class='footer'>
        <div class='point-out'
             v-if='store.loginData&&store.loginData.buyExplain'>{{store.loginData.buyExplain}}</div>
        <div class='aggregate '
             :class="[store.isIphoneX?'iphoneX-fixed-bottom':'']">
          <div>合计:
            <span>￥{{total}}</span>
          </div>
          <button formType="submit">提交订单</button>
        </div>
      </div>
    </form>
  </div>
</template>

<script>
import { YuYueTimeLiteapp, DiZhiLiteapp, OrderSave } from '@/api/api'

export default {
  data () {
    return {
      shoppingListData: null,
      total: 0,
      newTimeStamps: [],
      timeStampsIndex: 0,
      address: null,
      leaveWord: ''
    }
  },

  components: {},

  computed: {
    store () {
      return this.$store.state
    }
  },
  mounted () {
    this.leaveWord = ''
  },
  onShow () {
    this.getShoppingList()
    this.getTimeList()
    this.getAddress()
  },
  methods: {
    getShoppingList () {
      let res = this.$wx.getStore('confirmOrder')
      console.log(res)
      this.shoppingListData = res
      this.calculatePrice()
    },
    async  submitOrder (e) {
      let address = this.address
      if (!address) {
        this.$wx.textToast('地址不能为空')
        return false
      } else if (!this.newTimeStamps) {
        this.$wx.textToast('请选择配送时间段')
        return false
      } else if (address.LianXiRen === '') {
        this.$wx.textToast('收货人不能为空')
        return false
      } else if (address.DianHuaHao === '') {
        this.$wx.textToast('手机号码不能为空')
        return false
      }

      let newTimeStamps = this.newTimeStamps
      let timeStampsIndex = this.timeStampsIndex
      let shoppingListData = this.shoppingListData
      let detailJson = []
      // 普通商品
      for (let key of shoppingListData[0].arr) {
        detailJson.push({
          'SP_ID': key.SP_ID,
          'DB_ShuLiang': key.number,
          'DB_Type': key.settleStyle,
          'DB_Price': key.BJ_price,
          'DB_Money': (key.BJ_price * key.number).toFixed(2),
          'ZP_XID': key.settleStyle === '赠品' ? key.ZP_XID : 0
        })
      }
      // 标准商品
      for (let key of shoppingListData[0].bzArr) {
        detailJson.push({
          'SP_ID': key.SP_ID,
          'DB_ShuLiang': key.number,
          'DB_Type': '付款',
          'DB_Price': key.SP_price,
          'DB_Money': (key.SP_price * key.number).toFixed(2),
          'ZP_XID': 0,
          'JiaGeLeiXing': key.JiaGeLeiXing
        })
      }
      this.$wx.loading(true)

      OrderSave({
        KH_ID: address.KH_ID,
        formId: e.target.formId,
        DB_YueDingRiQi: newTimeStamps[timeStampsIndex],
        DB_BeiZhu: this.leaveWord,
        DB_YingShouJinEr: this.total,
        DB_DiZhi_ID: address.KH_DIZHI_ID,
        DB_address: address.Dizhi,
        DB_LianXiRen: address.LianXiRen,
        DB_TEL: address.DianHuaHao,
        detailJson: JSON.stringify(detailJson)
      }).then(res => {
        this.$wx.loading(false)
        if (res === '预约时间段错误') {
          let that = this
          setTimeout(() => {
            that.$wx.navigator(1)
          }, 1500)
        } else if (res === null) {
          this.$wx.redirectTo('/pages/order/payResult')
        }
      })
    },
    /** 下单时间初始化 */
    async getTimeList () {
      console.log('this.shoppingListData[0]', this.shoppingListData)

      let res = await YuYueTimeLiteapp(this.shoppingListData[0].title.KH_ID)
      let arr = []
      for (let key of res) {
        if (key.isCanBuy) {
          arr.push(key.YuYueDateStr)
        }
      }
      if (arr.length <= 0) {
        this.$wx.showModal('提示', '非配送时间段，无法下单', () => {
          this.$wx.navigator(1)
        })
      }
      this.newTimeStamps = arr
    },
    /** 选择下单时间段 */
    _newTimeStampsChange (e) {
      this.timeStampsIndex = Number(e.target.value)
    },
    /** 获取下单地址 */
    async getAddress () {
      if (!this.store.address) {
        let res = await DiZhiLiteapp(this.shoppingListData[0].title.KH_ID)
        this.$wx.getStore('addressList', res)
        for (let key of res) {
          if (key.DiZhiLeiXing === 'A') {
            this.address = key
          }
        }
        (!this.address) && (this.address = res[0])
      } else {
        this.address = this.store.address
      }
    },
    calculatePrice () {
      let shoppingListData = this.shoppingListData

      let total = 0
      for (let key of shoppingListData[0].arr) {
        if (key.isSelect) {
          total += Number((key.BJ_price * key.number).toFixed(2))
        }
      }
      for (let key of shoppingListData[0].bzArr) {
        if (key.isSelect) {
          total += Number((key.SP_price * key.number).toFixed(2))
        }
      }

      this.total = total.toFixed(2)
    },
    goTo (url) {
      this.$wx.navigator(url)
    }
  }
}
</script>
<style lang='scss' scoped>
@import '@/pages/chooseAnOffer/list.scss';
.confirmOrder {
  /*地址*/
  .address {
    padding: 26px 30px;
    background: #fff;
    > div {
      @include color666;
      @include fontSize(28);
      @include fjc(flex-start);
      margin-bottom: 13px;
      img {
        @include wh(44, 44);
        margin-right: 8px;
      }

      span {
        @include color111;
      }
    }
    > div:last-child {
      margin: 0;
    }
    > div:nth-child(2) {
      @include fjc;
      > div {
        @include fjc(center);
      }
    }
  }
  /*约定时间*/
  .agreedTime {
    background: #fff;
    padding: 26px 30px;
    border-top: 20px solid $mgColor;

    > div {
      @include color111;
      @include fjc(flex-start);
      @include fontSize(28);
      white-space: nowrap;
      position: relative;
      input {
        height: 60px;
        margin-left: 15px;
        padding: 0 30px;
        flex-grow: 1;
        @include border-all($lineColor, 0);
      }
      .selector {
        position: absolute;
        left: 0;
        top: 0;
        height: 60px;
        padding-left: 150px;
        @include fjc(center);
        z-index: 10;
        width: 100%;
        box-sizing: border-box;
      }
    }

    > div:last-child {
      margin-top: 13px;
      input {
        flex-grow: 1;
      }
    }
  }
  .purchaseGoods {
    border-top: 20px solid $mgColor;
  }
}
</style>